import { reactive, toRefs } from 'vue';
import IWebsocket from './chatWS'
import pinia from '@/store/index';
import { Chat } from '@/store/chat';
import { Local } from "@/utils/storage";
const chat = Chat(pinia);

const state_data: any = reactive({
  ChatGroupListReq: '',
  Input: null,
  per_page: 150,
  page: 1,
  groupChatitemList: [], // 分组聊天列表
  groupItem: '',    // 选中分组
  active: 0,    // 选中分组index
  chatitemList: [],
  keywordArr: [], //关键词列表
});

const usechatHooks = (state?: any) => {
  const getchatId = () => {
    if (state.deviceID > state.todeviceid) {
      return state.deviceID + '-' + state.todeviceid; //大的在前小的在后
    } else {
      return state.todeviceid + '-' + state.deviceID; //大的在前小的在后
    }
  };
  // 解析消息体
  const decodeContent = (data: any, name: string) => {
    let MessageOutputeItem = state.root.lookupType(name)
    const buffer1 = new Uint8Array(data);
    const decodedMessage2 = MessageOutputeItem.decode(buffer1);

    return MessageOutputeItem.toObject(decodedMessage2);
  }
  // 编码发送参数
  const encodeParams = (params: any, name: string) => {
    let item = state.root.lookupType(name)
    const errMsg = item.verify(params);
    if (errMsg) throw new Error(errMsg);
    const message = item.create(params);
    const buffer = item.encode(message).finish();
    return buffer;
  }
  const encodeInput = (type: any, request_id: any, data: any) => {
    state_data.Input = state.root.lookupType('Input');
    // Build payload object
    const payload = {
      type: type,
      requestid: request_id,
      data: data,
    };
    // Verify payload
    const errMsg = state_data.Input.verify(payload);
    if (errMsg) throw new Error(errMsg);
    // Create message
    const message = state_data.Input.create(payload);
    // Encode message
    const buffer = state_data.Input.encode(message).finish();
    return buffer;
  };
  // 公共发送方法  type:类型    payload 参数  Req请求类型
  const wsReqSend = (type: any, payload: any, Req: any) => {
    state.requestid++;
    const requestid = state.requestid;
    //编码消息体
    const decodedata = encodeParams(payload, Req);
    const encodedRequest = encodeInput(type, requestid, decodedata);
    IWebsocket.sendMessageHandler(encodedRequest);
  };
  // 获取聊天列表
  const getChatlist = (item?: any) => {
    const type = 13; //
    var payload = {
      deviceid: state.deviceID,
      groupid: item ? item.id : 0,
      page: 1,
      pagesize: 1000,
    };
    state_data.groupItem = item
    wsReqSend(type, payload, 'ChatGroupListReq');
  };
  const searchuser = (name: any) => {
    const type = 15; // 查询用户
    var payload = {
      username: name,
      deviceid: state.deviceID,
    };
    wsReqSend(type, payload, 'UserRoleReq');
  };
  const getChatMsg15 = (decodeobj1: any) => {
    const decodeobj00 = decodeContent(decodeobj1.data, 'UserRolesRsp');
    let ids = state.chatitemList.map((item: any) => item.roleid);
    if (
      decodeobj00 &&
      decodeobj00.roles &&
      !ids.includes(decodeobj00.roles[0].roleid)
    ) {
      const params = {
        ...decodeobj00.roles[0],
        TUsername: decodeobj00.roles[0].username,
        Tdeviceid: decodeobj00.roles[0].roleid,
        THeadPhoto: decodeobj00.roles[0].headphoto,
      };
      state.chatitemList = [params];
      // selectUser(params);
    }
    // state_data.groupList = decodeobj00.groupitem;
  };
  // 获取官方客服
  const getKfChat = () => {
    const type = 24; //
    var payload = {
      deviceid: state.deviceID,
    };
    wsReqSend(type, payload, 'KfRoleIdGetReq');
  };

  //  type13   聊天列表回执
  //deep -1代表上级
  // 1代表直属下级
  // 大于1代表 非直属下级
  const getChatMsg13 = (decodeobj1: any, tabsActive: any) => {
    state_data.active = tabsActive
    let usesrType = Local.get('usesrType')
    if (decodeobj1.data) {
      const decodeobj00 = decodeContent(decodeobj1.data, 'GroupChatListRsp');
      if (state_data.groupItem && state_data.groupItem.id) {
        state_data.groupChatitemList = decodeobj00.chatitem || [];
        state_data.chatitemList = decodeobj00.chatitem || [];
        console.log('获取的聊天列表', decodeobj00.chatitem)
        if (tabsActive != 0) {//非全部的分组不需要客服
          state.chatitemList = state_data.chatitemList
        }
      } else {
        state_data.chatitemList = decodeobj00.chatitem;
      }
      if (state_data.active == 0 && usesrType == 1) { // 好友列表（所有好友包括客服）保存
        chat.setChatitemList(state_data.chatitemList)
      }
      let bol = state_data.chatitemList.findIndex((item: any) => (item.iskf === 1 || item.deep === 0)) === -1 // 是否存在客服
      if (state_data.chatitemList && bol && state_data.active == 0) {
        if (usesrType == 1) {
          state.chatitemList = state_data.chatitemList
          return //客服自己不获取客服
        }
        getKfChat();
      }
      loopGetFirstMsg()
      //如果没有官方的历史聊天记录需要获取一下
    } else {
      if (usesrType == 1) {
        state.chatitemList = state_data.chatitemList
        return //客服自己不获取客服
      }
      state.chatitemList = state_data.chatitemList
      if (state_data.chatitemList.findIndex((item: any) => (item.iskf === 1 || item.deep === 0)) === -1) {
        getKfChat();
      }
    }
  };
  //  获取客服信息
  const getChatMsg24 = (decodeobj1: any) => {
    //先解析出消息体
    const UserRole = state.root.lookupType('UserRole');
    const buffer00 = new Uint8Array(decodeobj1.data);
    const decodedMessage00 = UserRole.decode(buffer00);
    const decodeobj00 = UserRole.toObject(decodedMessage00);
    const obj = {
      THeadPhoto: decodeobj00.headphoto,
      TUsername: decodeobj00.username,
      Tdeviceid: decodeobj00.roleid,
      chatid: '',
      deep: 0,
      deviceid: state.deviceID,
      id: 99999,
      unreadnums: decodeobj00.unreadnums,
    };
    if (state.deviceID > decodeobj00.roleid) {
      obj.chatid = state.deviceID + '-' + decodeobj00.roleid; //大的在前小的在后
    } else {
      obj.chatid = decodeobj00.roleid + '-' + state.deviceID; //大的在前小的在后
    }
    state_data.chatitemList.unshift(obj);
    state.chatitemList = state_data.chatitemList
    loopGetFirstMsg()
    if (state_data.active == 0) { // 好友列表（所有好友包括客服）保存
      chat.setChatitemList(state_data.chatitemList)
    }
    console.log('聊天列表加上客服', state_data.chatitemList)
  };

  //  同步历史数据
  const synchistorymsg = () => {
    //同步历史消息
    const type = 8; // 消息同步触发
    var payload = {
      chatid: getchatId(),
      perpage: state_data.per_page,
      page: 1,
    };
    //编码消息体
    wsReqSend(type, payload, 'SyncHistoryInput');
  };

  // 获取分组列表
  const getListGroup = () => {
    const type = 12; //
    var payload = {
      deviceid: state.deviceID,
      page: 1,
      pagesize: 100,
    };
    //编码消息体
    wsReqSend(type, payload, 'GroupListReq');
  };
  //  获取分组列表
  const getChatMsg12 = (decodeobj1: any) => {
    const decodeobj00 = decodeContent(decodeobj1.data, 'GroupListRsp');
    console.log('分组列表', decodeobj00)
    state.groupList = decodeobj00.groupitem
  };

  // 编辑聊天列表
  const editchat = (item: any) => {
    const type = 14; // 消息同步触发
    var payload = {
      id: item.id,
      deviceid: state.deviceID,
      chatgroupid: item.groupid || 0,
      unreadnums: item.unreadnums,
      sort: item.sort,
      istop: item.istop,
      enableflag: item.enableflag,
    }
    console.log('editchat type = 14 params ', payload)
    wsReqSend(type, payload, 'ChatItemModifyReq');
  }
  // 消息同步，已读
  const alreadread = (item: any) => {
    const type = 27; // item已读
    var payload = {
      deviceid: state.deviceID,
      chatid: item.chatid,
    }
    wsReqSend(type, payload, 'ReadChatItemReq');
  }
  const getFirstMsg = (chatid: any) => {
    if (!chatid) return
    const type = 8;
    var payload = {
      chatid,
      perpage: 1,
      page: 1,
    };
    wsReqSend(type, payload, 'SyncHistoryInput');
  };
  // 循环获取 chatitemList 第一条消息
  const loopGetFirstMsg = () => {
    state.chatitemList?.map((item: any) => {
      getFirstMsg(item.chatid)
    })
  };
  //处理聊天数据表情
  const initMessage = (text: any) => {
    const EMOJI_REMOTE_SRC = 'https://cdn.jsdelivr.net/npm/emoji-datasource-apple@6.0.1/img/apple/64';
    // 定义一个函数来将特定格式的字符串替换为图片
    function replaceWithEmojiImages(text: any) {
      // 定义一个正则表达式来匹配 /:1f600:/ 格式的字符串
      const regex = /\/:(.*?):\//g;
      if (text) {
        return text.replace(regex, (match: any) => {
          const value = match.slice(2, -2);
          const imgSrc = `${EMOJI_REMOTE_SRC}/${value}.png`;
          return `<img data-code="${value}" src="${imgSrc}?v=1}"  width="20" height="20" class="emoji-img"/>`;
        });
      }
    }
    const outputText = replaceWithEmojiImages(text);
    return outputText;
  };

  // 获取关键词列表
  const keywordList = () => {
    const type = 28; // 查询用户
    var payload = {
      deviceid: state.deviceID,
    };
    wsReqSend(type, payload, 'KwlistReq');
  };

  // 获取关键词列表
  const getkeywordList = (decodeobj1: any) => {
    const decodeobj00 = decodeContent(decodeobj1.data, 'KwlistReqRsp');
    state_data.keywordArr = decodeobj00.words?.map((item: any) => item.word) || [];
    Local.set('keywordArr', state_data.keywordArr)
    console.log('违禁词', state_data.keywordArr)
  };
  return {
    ...toRefs(state_data),
    getChatlist,
    loopGetFirstMsg,
    getChatMsg13,
    getChatMsg24,
    synchistorymsg,
    getListGroup,
    getChatMsg12,
    encodeParams,
    encodeInput,
    decodeContent,
    alreadread,
    editchat,
    searchuser,
    getChatMsg15,
    initMessage,
    getkeywordList,
    keywordList,
  };
};
export default usechatHooks;
